package cn.study.jmm;


import cn.study.cas.unsafe.UnsafeInstance;

/**
 * @Author     ：跟大佳一起学
 * @Description：有序性
 */
public class ReOrderTest {

    // TODO: 讲volatile
    private static int x = 0, y = 0;
    private static int a = 0, b = 0;

    /**
     * @description:
     * shortWait意义，线程1先执行，所以等一会线程2
     *  1、两个都增加volatile 可以解决问题
     *  2、复习下屏障，xy加volatile
     *  3、复习下屏障，ab加volatile
     *  4、UnsafeInstance.reflectGetUnsafe().storeFence 是否生效
     * @param args
     * @return void
     */
    public static void main(String[] args) throws InterruptedException {

        int i=0;
        while (true) {
            i++;
            x = y = a = b = 0;
            /**
             *  x,y的值是多少:
             */
            Thread thread1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    //用于调整两个线程的执行顺序,两个线程启动后的一个时差，保证同时运行
                    shortWait(20000);
                    a = 1;
                    UnsafeInstance.reflectGetUnsafe().storeFence();
                    x = b;
                }
            });
            Thread thread2 = new Thread(new Runnable() {
                @Override
                public void run() {
                    // 非常简短的一个指令不会引起cpu上下文切换
                    b = 1;
//                    UnsafeInstance.reflectGetUnsafe().storeFence();
//                    shortWait(20000);
                    y = a;
                }
            });
            thread1.start();thread2.start();
            thread1.join();thread2.join();
            System.out.println("第" + i + "次（" + x + "," + y + ")");
            if (x==0&&y==0){
                break;
            }
        }
    }

    public static void shortWait(long interval){
        long start = System.nanoTime();
        long end;
        do{
            end = System.nanoTime();
        }while(start + interval >= end);
    }

}
